package admin

import (
	"context"
	"encoding/json"
	"strconv"

	// "errors"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type MenuAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuAddLogic {
	return &MenuAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuAddLogic) MenuAdd(req *types.MenuPost) (resp *types.MenuItem, err error) {
	meta, _ := json.Marshal(req.Meta)
	menu := &model.AdminMenu{
		Meta:      string(meta),
		Component: req.Component,
		Name:      req.Name,
		ParentId:  0,
		Sort:      0,
		Path:      req.Path,
		Redirect:  "",
		DelState:  0,
		Version:   0,
	}

	res, err := l.svcCtx.Models.Menu.Insert(l.ctx, nil, menu)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "")
	}

	id, _ := res.LastInsertId()

	pid, _ := strconv.Atoi(req.ParentId)
	resp = &types.MenuItem{
		Id:        id,
		Pid:       int64(pid),
		Name:      menu.Name,
		Path:      menu.Path,
		Meta:      req.Meta,
		Component: req.Component,
		Redirect:  "",
		Icon:      req.Meta.Icon,
		Title:     req.Meta.Title,
		Type:      req.Meta.Type,
		Sort:      0,
		ApiList:   []*types.ApiList{},
		Children:  []*types.MenuItem{},
	}

	return
}
